import React, { useState, useRef, useEffect } from 'react';
import { 
  Code, 
  Copy, 
  Download, 
  RotateCcw, 
  Wand2, 
  FileText, 
  Palette,
  CheckCircle,
  AlertCircle
} from 'lucide-react';

const SvgEditor = ({ svgCode, onSvgChange, onFormatCode }) => {
  const [isCopied, setIsCopied] = useState(false);
  const [showExamples, setShowExamples] = useState(false);
  const textareaRef = useRef(null);

  const examples = [
    {
      name: '简单圆形',
      code: `<svg width="100" height="100" viewBox="0 0 100 100">
  <circle cx="50" cy="50" r="40" fill="#3b82f6" stroke="#1e40af" stroke-width="2"/>
</svg>`
    },
    {
      name: '彩色矩形',
      code: `<svg width="120" height="80" viewBox="0 0 120 80">
  <rect x="10" y="10" width="100" height="60" fill="#10b981" rx="8"/>
  <text x="60" y="45" text-anchor="middle" fill="white" font-size="14">Hello</text>
</svg>`
    },
    {
      name: '星形图案',
      code: `<svg width="100" height="100" viewBox="0 0 100 100">
  <polygon points="50,10 61,35 90,35 69,57 79,91 50,70 21,91 31,57 10,35 39,35" 
           fill="#f59e0b" stroke="#d97706" stroke-width="2"/>
</svg>`
    },
    {
      name: '渐变路径',
      code: `<svg width="120" height="120" viewBox="0 0 120 120">
  <defs>
    <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#8b5cf6;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#3b82f6;stop-opacity:1" />
    </linearGradient>
  </defs>
  <path d="M20,60 Q60,20 100,60 T100,100" stroke="url(#grad1)" stroke-width="4" fill="none"/>
</svg>`
    }
  ];

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(svgCode);
      setIsCopied(true);
      setTimeout(() => setIsCopied(false), 2000);
    } catch (err) {
      console.error('复制失败:', err);
    }
  };

  const handleDownload = () => {
    const blob = new Blob([svgCode], { type: 'image/svg+xml' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'svg-image.svg';
    a.click();
    URL.revokeObjectURL(url);
  };

  const handleReset = () => {
    onSvgChange('');
  };

  const handleExampleSelect = (example) => {
    onSvgChange(example.code);
    setShowExamples(false);
  };

  const handleFormat = () => {
    if (onFormatCode) {
      onFormatCode();
    }
  };

  // 自动调整文本域高度
  useEffect(() => {
    if (textareaRef.current) {
      textareaRef.current.style.height = 'auto';
      textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`;
    }
  }, [svgCode]);

  const isValidSvg = svgCode.trim() && svgCode.includes('<svg');

  return (
    <div className="bg-white rounded-2xl shadow-xl border border-gray-200/50 overflow-hidden">
      {/* 编辑器头部 */}
      <div className="bg-gray-50/50 px-4 py-3 border-b border-gray-200/50">
        <div className="flex items-center justify-between">
          <div className="flex items-center space-x-2">
            <Code className="w-5 h-5 text-gray-600" />
            <h3 className="font-semibold text-gray-900">SVG 代码编辑器</h3>
            {isValidSvg && (
              <div className="flex items-center space-x-1 text-green-600">
                <CheckCircle className="w-4 h-4" />
                <span className="text-sm">有效</span>
              </div>
            )}
            {!isValidSvg && svgCode.trim() && (
              <div className="flex items-center space-x-1 text-amber-600">
                <AlertCircle className="w-4 h-4" />
                <span className="text-sm">请输入有效的 SVG 代码</span>
              </div>
            )}
          </div>
          
          <div className="flex items-center space-x-2">
            <button
              onClick={() => setShowExamples(!showExamples)}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors"
            >
              <Palette className="w-4 h-4" />
              <span>示例</span>
            </button>
            
            <button
              onClick={handleFormat}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-purple-600 hover:bg-purple-50 rounded-lg transition-colors"
            >
              <Wand2 className="w-4 h-4" />
              <span>格式化</span>
            </button>
            
            <button
              onClick={handleCopy}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-green-600 hover:bg-green-50 rounded-lg transition-colors"
            >
              {isCopied ? <CheckCircle className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
              <span>{isCopied ? '已复制' : '复制'}</span>
            </button>
            
            <button
              onClick={handleDownload}
              disabled={!isValidSvg}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-blue-600 hover:bg-blue-50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
            >
              <Download className="w-4 h-4" />
              <span>下载</span>
            </button>
            
            <button
              onClick={handleReset}
              className="flex items-center space-x-1 px-3 py-1.5 text-sm text-gray-600 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors"
            >
              <RotateCcw className="w-4 h-4" />
              <span>清空</span>
            </button>
          </div>
        </div>
      </div>

      {/* 示例面板 */}
      {showExamples && (
        <div className="bg-blue-50/50 px-4 py-3 border-b border-blue-200/50">
          <div className="flex items-center space-x-2 mb-3">
            <FileText className="w-4 h-4 text-blue-600" />
            <span className="text-sm font-medium text-blue-900">选择示例模板</span>
          </div>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-2">
            {examples.map((example, index) => (
              <button
                key={index}
                onClick={() => handleExampleSelect(example)}
                className="text-left p-3 bg-white rounded-lg border border-blue-200/50 hover:border-blue-300 hover:bg-blue-50 transition-colors"
              >
                <div className="font-medium text-blue-900 text-sm">{example.name}</div>
                <div className="text-xs text-blue-600 mt-1 truncate">
                  {example.code.substring(0, 60)}...
                </div>
              </button>
            ))}
          </div>
        </div>
      )}

      {/* 代码编辑区域 */}
      <div className="p-4">
        <textarea
          ref={textareaRef}
          value={svgCode}
          onChange={(e) => onSvgChange(e.target.value)}
          placeholder="在此输入 SVG 代码...&#10;&#10;例如：&#10;<svg width='100' height='100' viewBox='0 0 100 100'>&#10;  <circle cx='50' cy='50' r='40' fill='#3b82f6'/>&#10;</svg>"
          className="w-full min-h-[300px] p-4 border border-gray-200 rounded-xl font-mono text-sm leading-relaxed resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          style={{ 
            fontFamily: 'Monaco, Menlo, "Ubuntu Mono", monospace',
            tabSize: 2
          }}
        />
      </div>

      {/* 底部状态栏 */}
      <div className="bg-gray-50/50 px-4 py-2 border-t border-gray-200/50">
        <div className="flex items-center justify-between text-xs text-gray-500">
          <div className="flex items-center space-x-4">
            <span>字符数: {svgCode.length}</span>
            <span>行数: {svgCode.split('\n').length}</span>
          </div>
          <div className="flex items-center space-x-2">
            <span>支持实时预览</span>
            <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default SvgEditor;
